package com.server.thisService.common;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;

import javax.annotation.PostConstruct;

//动态代理
public class DynamicInjectBean implements ApplicationContextAware {
    DefaultListableBeanFactory beanFactory = null;

    public void inject(Class cls) {
        try {
            BeanDefinitionBuilder builder = BeanDefinitionBuilder
                    .genericBeanDefinition(cls.getClass());
            beanFactory.registerBeanDefinition(cls.getName(),
                    builder.getBeanDefinition());
        } catch (Exception e) {
            throw new RuntimeException("创建service" + cls.getSimpleName()
                    + "异常:", e);
        }
    }

    @PostConstruct
    public void init() {
        inject(super.getClass());
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationcontext)
            throws BeansException {
        ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) applicationcontext;
        beanFactory = (DefaultListableBeanFactory) configurableApplicationContext
                .getBeanFactory();
    }
}
